/*
 * @Author: mayijun
 * @Date: 2022-05-14 11:12:52
 * @LastEditors: mayijun
 * @LastEditTime: 2022-07-11 14:55:15
 */
//指标组合弹出框组件
import { defineComponent, onMounted, PropType, reactive, ref, watch } from 'vue';
import './index.scss';
import Arithmetic from '@/components/Arithmetic/index';
import SelectIndex from '@/components/Arithmetic/components/SelectIndex';
import API from '@/services';
import { ElButton, ElDrawer, ElForm, ElFormItem, ElInput } from 'element-plus';
import _ from 'lodash';

const IndexGroupDrawer = defineComponent({
  name: 'IndexGroupDrawer',
  components: {
    Arithmetic,
    SelectIndex
  },
  props: {
    drawerVisible: {
      type: Boolean as PropType<boolean>,
      default: false
    },
    editData: {
      type: Object,
      default: () => { }
    },
    chosenDimensionIds: {
      type: Array,
      default: () => []
    },
    chosenMetricsIds: {
      type: Array,
      default: () => []
    },
    isMetricsFavorite: {
      type: Boolean,
      default: false
    },
  },
  emits: ['update:drawerVisible', 'submit'],
  setup: (props, { slots, attrs, emit }) => {

    let groupForm = ref();

    let state = reactive({
      pageNum: 1,
      pageSize: 10,
      keyword: "",
      form: {
        combinationName: '',
        arithmeticList: [] as any
      } as any,
      rules: {
        combinationName: [
          {
            required: true,
            message: '请输入组合名称',
            trigger: 'blur'
          }
        ],
        arithmeticList: [
          {
            required: true,
            message: '请添加运算逻辑',
            trigger: 'change'
          }
        ]
      },
      dialogVisible: false,
      indexList: []
    });

    const handleClose = () => {
      state.form.combinationName = '';
      state.form.arithmeticList = [];
      emit('update:drawerVisible', false);
    }
    const onSubmit = (form: any) => {
      groupForm.value.validate(async (bol: boolean) => {
        if (bol) {
          let item = _.cloneDeep(state.form);
          console.log(item);
          //计算规则
          let calculationFormula = item.arithmeticList
            ?.map(
              (v: any) =>
                `${v?.beforeSymbol || ''};${v?.afterSymbol || ''}${v?.numInput || ''
                }`
            )
            .join('');
          const { code, data }: any = await API.taskManagerV1.getCheckCalculationFormula({
            combination: calculationFormula
          });
          if (code === 200 && data) {
            item.calculationFormula = calculationFormula;
            emit('submit', item);
          } else {

          }
        }
      });
    }
    const indexChange = (v: any) => {
      console.log(v);
      console.log(props.chosenMetricsIds);

      state.form.arithmeticList.push({
        selectIndexName: v.label,
        selectIndexId: v.id,
        enName: v.enName,
        dataType: v.dataType,
        dataTypeId: v.dataTypeId,
        CombineEnumVal: v.aggregationId,
        CombineEnumName: v.aggregation,
      });
    }
    const changeIndex = (v: any, item: any, i: number) => {
      state.form.arithmeticList[i] = {
        ...state.form.arithmeticList[i],
        ...v,
        selectIndexName: v.selectIndexName || item.selectIndexName,
        selectIndexId: v.selectIndexId || item.selectIndexId
      };
    }

    watch(() => props.drawerVisible, (val: any) => {
      if (val) {
        let form = _.cloneDeep(props.editData);
        state.form = form;
        state.form.combinationName = props.editData?.combinationName || "";
        state.form.arithmeticList = props.editData.arithmeticList || [];
      }

    });

    return () => {
      return (
        <div class="index-group-drawer-wrap">
          <ElDrawer
            modelValue={props.drawerVisible}
            title="指标组合"
            size="680px"
            custom-class="system-drawer"
            close-on-click-modal={false}
            onClosed={() => {
              state.form.combinationName = '';
              state.form.arithmeticList = [];
              handleClose();
            }}
          >
            <ElForm rules={state.rules} ref={groupForm} model={state.form}>
              <ElFormItem prop="combinationName" label="组合名称">
                <ElInput size="large" v-model={state.form.combinationName} style="width: 230px"></ElInput>
              </ElFormItem>
              <ElFormItem prop="arithmeticList" label="组合逻辑">
                <div class="arithmetic">
                  <div class="arithmetic-container">
                    {state.form.arithmeticList.map((item: any, i: number) => (
                      <Arithmetic
                        onDel={() => { state.form.arithmeticList?.splice(i, 1) }}
                        arithmeticItem={item}
                        addCurrentIndex={item.selectIndexName}
                        isSubject={false}
                        isOnlyIndex={true}
                        onChangeIndex={(v) => changeIndex(v, item, i)}
                        useType={1}
                        key={i}
                      ></Arithmetic>
                    ))}

                    <el-button onClick={() => { state.dialogVisible = true }} type="text">
                      +添加
                    </el-button>
                    <SelectIndex
                      onIndexChange={indexChange}
                      v-model={[state.dialogVisible, 'dialogVisible']}
                      isSubject={false}
                      isOnlyIndex={true}
                      chosenDimensionIds={props.chosenDimensionIds}
                      chosenMetricsIds={props.chosenMetricsIds}
                      isMetricsFavorite={props.isMetricsFavorite}
                    />
                  </div>
                </div>
              </ElFormItem>
            </ElForm>
            <div class="footer-btn">
              <ElButton type="primary" onClick={() => { onSubmit('form') }}>组合</ElButton>
              <ElButton onClick={() => {
                state.form.combinationName = '';
                state.form.arithmeticList = [];
                handleClose();
              }}>取消</ElButton>
            </div>
          </ElDrawer>
        </div>
      );
    };
  }
});

export default IndexGroupDrawer;
